class Bridge {
    static setReceiveFunction(type, fn) {
        Bridge.receiveFunctions[type] = fn;
    }

    static setMinWin() {
        Bridge.jsToNative('setMinWin');
    }

    static closeWin() {
        Bridge.jsToNative('closeWin');
    }

    static receiveStartShare(data) {
        Bridge.jsToNative('receiveStartShare', data);
    }

    static receiveEndShare(data) {
        Bridge.jsToNative('receiveEndShare', data);
    }

    static startShare(shareType, isMinWin, callback) {
        const data = { IsMin: isMinWin, ShareType: shareType };
        Bridge.jsToNative('startShare', data, callback);
    }

    static endShare(callback) {
        Bridge.jsToNative('endShare', null, callback);
    }

    static importTemplate(callback) {
        Bridge.jsToNative('importTemplate', null, callback);
    }

    static downloadTemplate() {
        Bridge.jsToNative('downloadTemplate');
    }

    static importUsers(callback) {
        Bridge.jsToNative('importUsers', null, callback);
    }

    static exportUsers(users) {
        Bridge.jsToNative('exportUsers', { Users: users });
    }

    static exportVotes(votes) {
        Bridge.jsToNative('exportVotes', { Votes: votes });
    }

    static exportUserSigns(userSigns) {
        Bridge.jsToNative('exportUserSigns', { UserSigns: userSigns });
    }

    static exportVoteResult(voteResult) {
        Bridge.jsToNative('exportVoteResult', { VoteResult: voteResult });
    }

    static exportScoreResult(scoreResult) {
        Bridge.jsToNative('exportScoreResult', { ScoreResult: scoreResult });
    }

    static exportScores(scores) {
        Bridge.jsToNative('exportScores', { Scores: scores });
    }

    static openFile(data) {
        Bridge.jsToNative('openFile', data);
    }

    static jsToNative(type, data, callback) {
        if (window.jsToNative && window.jsToNative[type]) {
            window.jsToNative[type](data);
        }
        else if (window.chrome && window.chrome.webview) {
            window.chrome.webview.postMessage(JSON.stringify({ type, data }));
            if (callback) Bridge.setReceiveFunction(type, callback);
        }
    }
}

Bridge.receiveFunctions = [];

Bridge.setReceiveFunction('endReceShare', () => {
    window.setEndReceShare && window.setEndReceShare();
    window.isReceShare = false;
});

Bridge.setReceiveFunction('startReceShare', () => {
    window.setStartReceShare && window.setStartReceShare();
    window.isReceShare = true;
});

if (window.chrome && window.chrome.webview) {
    window.chrome.webview.addEventListener('message', arg => {
        const d = arg.data;
        if (!d) return;

        const msg = JSON.parse(d);
        const fn = Bridge.receiveFunctions[msg.type];
        fn && fn(msg.data);
    });
}

export default Bridge;